
import baseAppInit from "../../app/base/baseAppInit";
import { app } from "../../app/app";
import colorShapRing from "../../app/com/render/colorShapRing";

const { ccclass, property } = cc._decorator;

function isWeChat(): boolean {
    return window['wx'] && !window['tt'];
}

@ccclass
export default class AppInit extends baseAppInit {
    @property(cc.Node)
    private logoNode: cc.Node = null;

    @property(cc.Node)
    private progressNode: cc.Node = null;

    @property(cc.Label)
    private progressTitle: cc.Label = null;

    @property(colorShapRing)
    private progressRing = null;

    private maxpro = 0;
    private progress = 0;
    private speed = 0.02;
    private ready = false;

    // 获得用户资源总量，这里返回几，就需要自行调用几次nextInit
    protected getUserAssetNum() {
        // if (isWeChat()) {
        //     return 3;
        // } else {
        //     return 1;
        // }
        return 1;
    }

    protected update() {
        if (!this.ready) {
            return;
        }
        if (this.progress < this.maxpro) {
            this.progress += this.speed;
            this.progress = Math.min(1, this.progress);
            this.progressTitle.string = `${Math.floor(this.progress * 100)}%`;
            this.progressRing.progress = this.progress;
        } else if (this.ready && this.progress == 1) {
            this.ready = false;
            this.scheduleOnce(this.nextInit, 0.1);
        }
    }

    protected onProgress(completed, total) {
        if (completed <= total - 1) {
            this.maxpro = completed / (total - 1);
        }
        cc.log('onProgress', completed, total)
    }

    protected onUserInit(index) {
        if (isWeChat()) {
            this.loadSubpackage(index, () => this.nextInit());
        }
    }

    protected loadSubpackage(index, nextInit) {

    }

    onLoad() {
        this.logoNode.getComponentsInChildren(cc.Label).forEach(label => label.string = app.setting.name);

        this.progressTitle.string = '0%';
        this.progressRing.progress = 0;
        this.progressNode.opacity = 0;
        this.logoNode.opacity = 0;
    }

    start() {
        this.startInit();
        app.lib.task.createSync()
            .add((next) => {
                cc.tween(this.logoNode)
                    .to(0.25, { opacity: 255 })
                    .call(next)
                    .start()
            })
            .add(next => this.scheduleOnce(next, 1))
            .add((next) => {
                cc.tween(this.logoNode)
                    .to(0.25, { opacity: 0 })
                    .call(next)
                    .start()
            })
            .add((next) => {
                cc.tween(this.progressNode)
                    .to(0.25, { opacity: 255 })
                    .call(next)
                    .start()
            })
            .start(() => {
                this.ready = true;
            })
    }
}